package com.yami.shop.smsserver.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.yami.shop.common.bean.TencentSMS;
import com.yami.shop.common.config.Constant;
import com.yami.shop.config.ShopConfig;
import com.yami.shop.service.SysConfigService;
import com.yami.shop.smsserver.SmsServer;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 腾讯短信发送接口
 */
@Service
@Slf4j
@AllArgsConstructor
public class TenecntSmsServerImpl implements SmsServer {

    private ShopConfig shopConfig;
    private SysConfigService sysConfigService;
    @Override
    public Boolean sendSms(String mobile, String templateCode, Map<String, String> params) {
        TencentSMS tencentSMS = null;
        try {
            tencentSMS = shopConfig.getTencentSms();
        }catch (Exception e){
            sysConfigService.removeSysConfig(Constant.TENCENTSMS_CONFIG);
            tencentSMS = shopConfig.getTencentSms();
        }
        //获取模板CODE
        templateCode = JSONObject.parseObject(templateCode).getString(Constant.TENCENTSMS_CONFIG);
        if (ObjectUtil.isEmpty(templateCode)) {
            log.error("该信息没有绑定模板ID");
            return false;
        }
        //测试号码
        String smsWhitelist = shopConfig.getSmsWhitelist();
        if (ObjectUtil.isNotEmpty(smsWhitelist) && matches(mobile, Arrays.asList(smsWhitelist.split(",")))) {
            return true;
        }else{
            //正式号码发送短信
            try {
                SmsSingleSender sender = new SmsSingleSender(tencentSMS.getAppId(), tencentSMS.getApikey());
                //参数转换
                ArrayList<String> parms = new ArrayList<>();
                params.entrySet().forEach(s -> {
                    parms.add(s.getValue());
                });
                SmsSingleSenderResult result = sender.sendWithParam("86", mobile, Integer.parseInt(templateCode), parms, tencentSMS.getSmsSign(), "", "");
                log.info("发送短信信息{}",result.errMsg);
                log.info("发送短信信息JSON={}",JSONObject.toJSONString(result));
                if (!"OK".equals(result.errMsg)) {
                    return false;
                }
                return true;
            } catch (Exception e) {
                log.error("发送短信失败，请稍后再试：" + e.getMessage());
                return false;
            }
        }
    }
    /**
     * 查找指定字符串是否匹配指定字符串列表中的任意一个字符串
     *
     * @param str 指定字符串
     * @param strs 需要检查的字符串数组
     * @return 是否匹配
     */
    private  boolean matches(String str, List<String> strs)
    {
        if (ObjectUtil.isEmpty(str) || ObjectUtil.isEmpty(strs))
        {
            return false;
        }
        for (String pattern : strs)
        {
            if (isMatch(pattern, str))
            {
                return true;
            }
        }
        return false;
    }
    /**
     * 判断url是否与规则配置:
     * ? 表示单个字符;
     * * 表示一层路径内的任意字符串，不可跨层级;
     * ** 表示任意层路径;
     *
     * @param pattern 匹配规则
     * @param url 需要匹配的url
     * @return
     */
    private boolean isMatch(String pattern, String url)
    {
        AntPathMatcher matcher = new AntPathMatcher();
        return matcher.match(pattern, url);
    }
}
